import datetime

from flask import jsonify, request

from db.dao import StockMarketDao, IndustrySectorFundsDao, StockInfoDao, IndustryInfoDao, StockFundsDao, \
    MarketWorkDayDao
from utils.util import FlaskTool
from web import custom


@custom.route('/common/last_trading_date')
def get_last_trading_date():
    '''
    股票市场最近的交易日期
    :return:
    '''
    return str(MarketWorkDayDao().queryLastWorkDay(datetime.date.today()))


@custom.route('/common/trading_dates')
def get_trading_dates():
    '''
    股票市场最近几周日期集合(5交易日/一周)
    :return:
    '''
    weeks = request.args.get('weeks', 1, type=int)
    trading_day_list = MarketWorkDayDao().queryLastWorkDay(datetime.date.today(), limit=weeks * 5)
    return jsonify(trading_day_list)


@custom.route('/board/market')
def marketBoard():
    '''
    股票市场单日涨幅查询
    :return:
    '''
    pagination = StockMarketDao().queryByPage(request.args)
    return jsonify(FlaskTool.paginatioToList(pagination))


@custom.route('/board/industry')
def industryBoard():
    '''
    股票行业单日涨幅查询
    :return:
    '''
    pagination = IndustrySectorFundsDao().queryByPage(request.args)
    return jsonify(FlaskTool.paginatioToList(pagination))



@custom.route('/board/stock-fund')
def industryStock():
    '''
    股票行业单日涨幅查询
    :return:
    '''
    pagination = StockFundsDao().queryByPage(request.args)
    return jsonify(FlaskTool.paginatioToList(pagination))


@custom.route('/board/stock-info')
def stockInfoBoard():
    '''
    股票基础信息查询
    :return:
    '''
    page = StockInfoDao().queryByPage(request.args)
    return jsonify(FlaskTool.paginatioToList(page))


@custom.route('/board/industry-info', methods=['GET', 'POST'])
def industryInfoBoard():
    '''
    行业下拉框
    :return:
    '''
    list = IndustryInfoDao().findAll()

    return jsonify(modelList(list))


def modelList(result):
    list = [{'name': '--全部--', 'value': ''}]
    for row in result:
        dict = {}
        items = row.__dict__.items()
        for k, v in items:
            if k == 'name':
                dict['name'] = v
                dict['value'] = v
        list.append(dict)

    return list
